import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, Card, Tag, Empty, Tabs, Badge } from 'antd-mobile'
import { 
  LeftOutline, 
  ClockCircleOutline, 
  CalendarOutline, 
  PlayOutline,
  DeleteOutline,
  EditSOutline,
  CheckCircleOutline,
  CloseCircleOutline
} from 'antd-mobile-icons'
import dataService, { type Training } from '../../services/dataService'
import './training-management.css'

interface TrainingBooking {
  id: string
  training: Training
  scheduledDate: Date
  scheduledTime: string
  status: 'upcoming' | 'completed' | 'cancelled'
  createdAt: Date
}

const TrainingManagement = () => {
  const navigate = useNavigate()
  const [activeTab, setActiveTab] = useState('upcoming')
  const [bookings, setBookings] = useState<TrainingBooking[]>([])
  const [stats, setStats] = useState({
    total: 0,
    completed: 0,
    upcoming: 0,
    cancelled: 0,
    completionRate: 0
  })

  // 模拟训练预定数据
  useEffect(() => {
    const mockBookings: TrainingBooking[] = [
      {
        id: '1',
        training: dataService.getTrainingById(1)!,
        scheduledDate: new Date(2024, 11, 15),
        scheduledTime: '09:00',
        status: 'upcoming',
        createdAt: new Date(2024, 11, 10)
      },
      {
        id: '2',
        training: dataService.getTrainingById(2)!,
        scheduledDate: new Date(2024, 11, 12),
        scheduledTime: '14:00',
        status: 'completed',
        createdAt: new Date(2024, 11, 8)
      },
      {
        id: '3',
        training: dataService.getTrainingById(3)!,
        scheduledDate: new Date(2024, 11, 18),
        scheduledTime: '16:00',
        status: 'upcoming',
        createdAt: new Date(2024, 11, 12)
      },
      {
        id: '4',
        training: dataService.getTrainingById(4)!,
        scheduledDate: new Date(2024, 11, 8),
        scheduledTime: '10:00',
        status: 'cancelled',
        createdAt: new Date(2024, 11, 5)
      },
      {
        id: '5',
        training: dataService.getTrainingById(5)!,
        scheduledDate: new Date(2024, 11, 10),
        scheduledTime: '18:00',
        status: 'completed',
        createdAt: new Date(2024, 11, 6)
      }
    ]

    setBookings(mockBookings)

    // 计算统计数据
    const total = mockBookings.length
    const completed = mockBookings.filter(b => b.status === 'completed').length
    const upcoming = mockBookings.filter(b => b.status === 'upcoming').length
    const cancelled = mockBookings.filter(b => b.status === 'cancelled').length
    const completionRate = total > 0 ? Math.round((completed / total) * 100) : 0

    setStats({ total, completed, upcoming, cancelled, completionRate })
  }, [])

  const getFilteredBookings = () => {
    return bookings.filter(booking => {
      if (activeTab === 'all') return true
      return booking.status === activeTab
    })
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'upcoming': return '#ff6b35'
      case 'completed': return '#52c41a'
      case 'cancelled': return '#ff4d4f'
      default: return '#666'
    }
  }

  const getStatusText = (status: string) => {
    switch (status) {
      case 'upcoming': return '即将开始'
      case 'completed': return '已完成'
      case 'cancelled': return '已取消'
      default: return status
    }
  }

  const handleStartTraining = (booking: TrainingBooking) => {
    navigate(`/training-session?id=${booking.training.id}`)
  }

  const handleReschedule = (booking: TrainingBooking) => {
    navigate(`/schedule-training?id=${booking.training.id}&reschedule=${booking.id}`)
  }

  const handleCancel = (bookingId: string) => {
    setBookings(prev => prev.map(booking => 
      booking.id === bookingId 
        ? { ...booking, status: 'cancelled' as const }
        : booking
    ))
  }

  const handleViewDetails = (booking: TrainingBooking) => {
    navigate(`/training-detail?id=${booking.training.id}`)
  }

  const formatDate = (date: Date) => {
    return date.toLocaleDateString('zh-CN', {
      month: 'short',
      day: 'numeric',
      weekday: 'short'
    })
  }

  const isToday = (date: Date) => {
    const today = new Date()
    return date.toDateString() === today.toDateString()
  }

  // const isPast = (date: Date) => {
  //   const today = new Date()
  //   today.setHours(0, 0, 0, 0)
  //   return date < today
  // }

  const tabItems = [
    { key: 'upcoming', title: '即将开始', badge: stats.upcoming },
    { key: 'completed', title: '已完成', badge: stats.completed },
    { key: 'cancelled', title: '已取消', badge: stats.cancelled },
    { key: 'all', title: '全部', badge: stats.total }
  ]

  return (
    <div className="management-page">
      {/* 顶部导航 */}
      <div className="management-header">
        <button className="back-btn" onClick={() => navigate(-1)}>
          <LeftOutline />
        </button>
        <div className="title">训练管理</div>
        <div style={{ width: 24 }} />
      </div>

      <div className="management-content">
        {/* 统计卡片 */}
        <Card className="stats-card">
          <div className="stats-grid">
            <div className="stat-item">
              <div className="stat-number">{stats.total}</div>
              <div className="stat-label">总训练</div>
            </div>
            <div className="stat-item">
              <div className="stat-number">{stats.completed}</div>
              <div className="stat-label">已完成</div>
            </div>
            <div className="stat-item">
              <div className="stat-number">{stats.upcoming}</div>
              <div className="stat-label">待训练</div>
            </div>
            <div className="stat-item">
              <div className="stat-number">{stats.completionRate}%</div>
              <div className="stat-label">完成率</div>
            </div>
          </div>
        </Card>

        {/* 标签页 */}
        <div className="tabs-container">
          <Tabs 
            activeKey={activeTab} 
            onChange={setActiveTab}
            style={{
              '--active-title-color': '#ff6b35',
              '--active-line-color': '#ff6b35'
            }}
          >
            {tabItems.map(tab => (
              <Tabs.Tab 
                key={tab.key} 
                title={
                  <div className="tab-title">
                    {tab.title}
                    {tab.badge > 0 && (
                      <Badge content={tab.badge} style={{ marginLeft: 4 }} />
                    )}
                  </div>
                }
              />
            ))}
          </Tabs>
        </div>

        {/* 训练列表 */}
        <div className="training-list">
          {getFilteredBookings().length === 0 ? (
            <Empty
              description={`暂无${tabItems.find(t => t.key === activeTab)?.title}的训练`}
              style={{ padding: '40px 0' }}
            />
          ) : (
            getFilteredBookings().map((booking) => (
              <Card key={booking.id} className="training-card">
                <div className="training-item">
                  <div className="training-main">
                    <img 
                      src={booking.training.cover} 
                      alt={booking.training.title}
                      className="training-thumbnail"
                    />
                    <div className="training-info">
                      <h3 className="training-name">{booking.training.title}</h3>
                      <div className="training-meta">
                        <div className="meta-item">
                          <CalendarOutline />
                          <span>
                            {formatDate(booking.scheduledDate)}
                            {isToday(booking.scheduledDate) && (
                              <span className="today-label">今天</span>
                            )}
                          </span>
                        </div>
                        <div className="meta-item">
                          <ClockCircleOutline />
                          <span>{booking.scheduledTime}</span>
                        </div>
                      </div>
                      <div className="training-tags">
                        <Tag 
                          color={getStatusColor(booking.status)}
                          fill="outline"
                          style={{ fontSize: '11px' }}
                        >
                          {getStatusText(booking.status)}
                        </Tag>
                        <Tag fill="outline" style={{ fontSize: '11px' }}>
                          {booking.training.duration}
                        </Tag>
                      </div>
                    </div>
                  </div>

                  {/* 操作按钮 */}
                  <div className="training-actions">
                    {booking.status === 'upcoming' && (
                      <>
                        <Button
                          size="mini"
                          color="primary"
                          fill="outline"
                          onClick={() => handleStartTraining(booking)}
                          style={{ borderColor: '#ff6b35', color: '#ff6b35' }}
                        >
                          <PlayOutline /> 开始
                        </Button>
                        <Button
                          size="mini"
                          fill="outline"
                          onClick={() => handleReschedule(booking)}
                        >
                          <EditSOutline /> 改期
                        </Button>
                        <Button
                          size="mini"
                          color="danger"
                          fill="outline"
                          onClick={() => handleCancel(booking.id)}
                        >
                          <DeleteOutline /> 取消
                        </Button>
                      </>
                    )}
                    {booking.status === 'completed' && (
                      <>
                        <Button
                          size="mini"
                          fill="outline"
                          onClick={() => handleViewDetails(booking)}
                        >
                          <CheckCircleOutline /> 查看
                        </Button>
                        <Button
                          size="mini"
                          color="primary"
                          fill="outline"
                          onClick={() => navigate(`/schedule-training?id=${booking.training.id}`)}
                          style={{ borderColor: '#ff6b35', color: '#ff6b35' }}
                        >
                          <PlayOutline /> 再练
                        </Button>
                      </>
                    )}
                    {booking.status === 'cancelled' && (
                      <>
                        <Button
                          size="mini"
                          fill="outline"
                          onClick={() => handleViewDetails(booking)}
                        >
                          <CloseCircleOutline /> 详情
                        </Button>
                        <Button
                          size="mini"
                          color="primary"
                          fill="outline"
                          onClick={() => navigate(`/schedule-training?id=${booking.training.id}`)}
                          style={{ borderColor: '#ff6b35', color: '#ff6b35' }}
                        >
                          <PlayOutline /> 重新预定
                        </Button>
                      </>
                    )}
                  </div>
                </div>
              </Card>
            ))
          )}
        </div>
      </div>
    </div>
  )
}

export default TrainingManagement
